<template>
  <div>
    <!--     导航栏/资源配置 -->
    <el-tree
        :props="{label:'resourcesName'}"
        node-key="id"
        show-checkbox
        ref="tree"
        :data="data"
    >
    </el-tree>
    <el-row style="text-align: center;margin-top: 20px">
      <div>
        <el-button :loading="loading" type="primary" style="margin-right: 30px" @click="confirm">{{ $t('确认') }}
        </el-button>
        <el-button type="info" @click="getData">{{ $t('重置') }}</el-button>
      </div>
    </el-row>
  </div>
</template>

<script>
import {appResourcesControlList,updateAppResourcesControl} from '@/api/product'

export default {
  props: ['panePermiss'],
  data() {
    return {
      data: [],
      loading: false,
      defaultCheck: [],
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await appResourcesControlList({
        productId: this.$route.query.productId
      })
      if (res.code === 1) {
        const data = res.data.filter(father => {
          const childArr = res.data.filter(child => father.id === child.type)
          childArr.length > 0 ? father.children = childArr : ''

          return father.type === 0
        })
        this.data = data
        this.$nextTick(() => {
          const keys = res.data.filter(item => item.id && item.status === 1).map(item => item.id).sort((a,b)=>a-b)
          keys.forEach(item => {
            this.$refs.tree.setChecked(item, true)
          })
        })
      }
    },
    async confirm() {
      this.loading = true
      const treeData = []
      const treeKeys = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      const list = (data) => {
        for (let i = 0; i < data.length; i++) {
          if (data[i].children && data[i].children.length) {
            list(data[i].children)
          }
          treeData.push({
            status: treeKeys.indexOf(data[i].id) !== -1 ? 1  : 2,
            id: data[i].id,
            resourcesFieldName: data[i].resourcesFieldName,
            productId: data[i].productId
          })
        }
      }
      list(this.data)
      const res = await updateAppResourcesControl(treeData)
      if (res.code === 1) {
        this.loading = false
        this.$message.success(this.$t('修改成功'))
        this.getData()
      } else {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tree {
  margin-top: 10px;

  .tree_item {
    margin: 10px 0 0 40px;
  }
}
</style>
